package vip.xiaonuo.modular.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vip.xiaonuo.modular.qryNum.QryNumConst;

import java.util.*;
import java.util.function.Consumer;

/**
 * HttpClient发送GET、POST请求
 * @Author libin
 * @CreateDate 2018.5.28 16:56
 */
public class  HttpClientService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
    /**
     * 返回成功状态码
     */
    private static final int SUCCESS_CODE = 200;

    public static Object sendGet(String url, List<NameValuePair> nameValuePairList, Consumer<HttpGet> consumer) throws Exception {
        JSONObject jsonObject = null;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            /**
             * 创建HttpClient对象
             */
            client = new SSLClient();
            /**
             * 创建URIBuilder
             */
            URIBuilder uriBuilder = new URIBuilder(url);
            /**
             * 设置参数
             */
            //    uriBuilder.addParameters(nameValuePairList);
            /**
             * 创建HttpGet
             */
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            if (Objects.nonNull(consumer)) {
                consumer.accept(httpGet);
            }

            /**
             * 请求服务
             */
            response = client.execute(httpGet);
            /**
             * 获取响应吗
             */
            int statusCode = response.getStatusLine().getStatusCode();

            if (SUCCESS_CODE == statusCode){
                /**
                 * 获取返回对象
                 */
                HttpEntity entity = response.getEntity();
                /**
                 * 通过EntityUitls获取返回内容
                 */
                String result = EntityUtils.toString(entity,"UTF-8");
                /**
                 * 转换成json,根据合法性返回json或者字符串
                 */
                try{
                    jsonObject = JSONObject.parseObject(result);
                    return jsonObject;
                }catch (Exception e){
                    return result;
                }
            }else{
                LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败！");
            }
        }catch (Exception e){
            LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
        } finally {
            response.close();
            client.close();
        }
        return null;
    }

    /**
     * 发送GET请求
     * @param url   请求url
     * @param nameValuePairList    请求参数
     * @return JSON或者字符串
     * @throws Exception
     */
    public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{
        return sendGet(url, nameValuePairList, (httpGet ->  {
            httpGet.setHeader(new BasicHeader("Cookie","HSH_YUNSION_SESSIONID=1F042C582D1782801A32035C1574657E4D392A8E1D027FF1EA8FF; JSESSIONID=A56F7640BF992C311EA4DF073E202BCE"));
            //HSH_YUNSION_SESSIONID=1F042C582D1782801A32035C1574657E4D392A8E1D027FF1EA8FF; JSESSIONID=A56F7640BF992C311EA4DF073E202BCE
            // HSH_YUNSION_SESSIONID=1700265F20138E8D1A3A054D4177866F3B8501549B44F5F60E722; fromAPP=1; _r_H5ReqSeq=1666228615.AGZXQ01160.20220210161409201; JSESSIONID=2B9159C7B889AADC5EDE5F01682AF1B4
        }));
    }

    public static String doPost(String url, String map, String charset, Map<String, String> header) {
        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            if (Objects.nonNull(header)) {
                for (Map.Entry<String, String> entry: header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(map);
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 发送POST请求
     * @param url
     * @param nameValuePairList
     * @return JSON或者字符串
     * @throws Exception
     */
    public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{
        JSONObject jsonObject = null;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            /**
             *  创建一个httpclient对象
             */
            client = new SSLClient();
            /**
             * 创建一个post对象
             */
            HttpPost post = new HttpPost(url);
            /**
             * 包装成一个Entity对象
             */

         //   StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
            /**
             * 设置请求的内容
             */
         //   post.setEntity(entity);
            /**
             * 设置请求的报文头部的编码
             */
            post.setHeader(new BasicHeader("Content-Type", "application/json"));
            /**
             * 设置请求的报文头部的编码
             */
            post.setHeader(new BasicHeader("Content-Encoding", "identity"));

            post.setHeader(new BasicHeader("yiuvt5t8", "BssuUA97-bx-HqfIjXptwDOnd3CQQURdwNOqBjKcWWdniZ0hOlyG3BX9-VbNdIwXNyrsWjbKnCeTsukNMtOvwT60Z5OkWUakXOixusegUE3QibCTUnaAs9JRMDsbbqhY4GGWUCbqMtTPtAiM8vQEOx_rCTBHuW6rjXTxsx__M7Rypkn6jPS..NlTnbzvMGVBS8y3Nr1K5olNYVvfyk8znPsFichb7awGOU6LvOWp3_oHctjjwSQ1ORhuhU1y4ajti7QyUzfPBr_thPLHbHr0HHHOxrCxa_psy8mAmAXPi5jdrFjkwthYREeBCu1axZ8EVVpcw6FrSSizfD_pv5B6V76LUTDR52zHwlX7ithnIVSqEHuI3JTiBL6rcmwohFp7-b-Jj4jyXM2IXl4ik84dmC6YBqaYNHKwoM_tF0EW3eqdIDLfRh2Nl77t8nAYhTbeEyIyPuHXjECUUNByu3aO-zqhC1a4S9DpedC95o_Hz10e8-fbgHM2eZKr5hQp-QuqbCv140TzL-1Xsp8ksghn4zej1oov89Jg0G-td8tpDGeNTGPpR7B4I_tG_p6LnFIAxJtP3wrVgHt65nWmO3oztorZeS79OYx6DknwSLjngtIoXtWx5B_rK6uuJNRWq_ygQe9RCrPRdsUjS5VIJKs754UG6rVmj3ODedqolnhSYO2T3vQyB8LFn0ozl9MdsSbH0ycgu-G4mT8qeX9ghQYP_8oT6gBu_q3cY2PtovA3MzN3tss5W_vNM7cZyn6Gr6HT5ctXB18ddqYwi7UC4BW8wK8iIfTbGLr1zf36Csumzd7cdFM6RBrOpZ60xqIEAYFBwLJSVeZeI..7UT12XSW"));
            post.setHeader(new BasicHeader("X-App-Sign", "01:76:76:E2:D0:9B:61:95:55:8D:BD:7B:30:55:DE:66:19:63:95:51"));
            post.setHeader(new BasicHeader("X-License-Key", "f944e311895b4f8cb6233c4fd351713f"));
          /*  post.setHeader(new BasicHeader("yiuvt5t8", ""));
            post.setHeader(new BasicHeader("yiuvt5t8", ""));
            post.setHeader(new BasicHeader("yiuvt5t8", ""));
            post.setHeader(new BasicHeader("yiuvt5t8", ""));
            post.setHeader(new BasicHeader("yiuvt5t8", ""));*/
            /**
             * 执行post请求
             */
            response = client.execute(post);
            /**
             * 获取响应码
             */
            int statusCode = response.getStatusLine().getStatusCode();
            if (SUCCESS_CODE == statusCode){
                /**
                 * 通过EntityUitls获取返回内容
                 */
                String result = EntityUtils.toString(response.getEntity(),"UTF-8");
                /**
                 * 转换成json,根据合法性返回json或者字符串
                 */
                try{
                    jsonObject = JSONObject.parseObject(result);
                    return jsonObject;
                }catch (Exception e){
                    return result;
                }
            }else{
                LOGGER.error("HttpClientService-line: {}, errorMsg：{}", 146, "POST请求失败！");
            }
        }catch (Exception e){
            LOGGER.error("HttpClientService-line: {}, Exception：{}", 149, e);
        }finally {
            response.close();
            client.close();
        }
        return null;
    }

    /**
     * 组织请求参数{参数名和参数值下标保持一致}
     * @param params    参数名数组
     * @param values    参数值数组
     * @return 参数对象
     */
    public static List<NameValuePair> getParams(Object[] params, Object[] values){
        /**
         * 校验参数合法性
         */
        boolean flag = params.length>0 && values.length>0 &&  params.length == values.length;
        if (flag){
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for(int i =0; i<params.length; i++){
                nameValuePairList.add(new BasicNameValuePair(params[i].toString(),values[i].toString()));
            }
            return nameValuePairList;
        }else{
            LOGGER.error("HttpClientService-line: {}, errorMsg：{}", 197, "请求参数为空且参数长度不一致");
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String json = "{\n" +
                "\t\"publicData\": {\n" +
                "\t\t\"reqTime\": \"20220219143038\",\n" +
                "\t\t\"reqSeq\": \"20220219143038htSearch\",\n" +
                "\t\t\"activityId\": \"htSearch\",\n" +
                "\t\t\"appid\": \"cxcc7a4a1608df4431\",\n" +
                "\t\t\"serviceId\": \"ability_customize\",\n" +
                "\t\t\"version\": \"1.0\"\n" +
                "\t},\n" +
                "\t\"data\": {\n" +
                "\t\t\"servicecode\": \"Fe90322c88553590\",\n" +
                "\t\t\"params\": {\n" +
                "\t\t\t\"mobile\": \"18666095339\"\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";

        Map<String, String> header = new HashMap<>(16);
        for (QryNumConst value : QryNumConst.values()) {
            header.put(value.name, value.value);
        }
//        String s = doPost("https://gd.10086.cn/apph5/openapi/app/handle", json, "utf-8", header);
//
//        for (int i=0; i < 100; i++) {
//            doPost("https://gd.10086.cn/apph5/openapi/app/handle", json, "utf-8", header);
//        }
        System.out.println(System.nanoTime());
//        System.out.println(s);
    }


}
